<?php
/**
 * https://gitee.com/Mao02
 * http://www.mao02.win/
 * jay_fun 410136330@qq.com
 * Date: 2018/4/9 0009
 * Time: 上午 0:02
 */

namespace app\common\service;

use app\common\model\SystemAdmin;
use think\Db;
use think\facade\Response;
use think\facade\Session;

/**
 * 管理员权限验证服务
 * Class Auth
 * @package jay\Surport
 */
class Auth {

    /**
     * 执行验证
     * @param $path
     * @return bool|\think\response|\think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
	public function auth($path) {

        $username = Session::get('admin.username');

        if ($username === "admin"){
            return true;
        }

		$admin_id = Session::get('admin.id');

		$node = Db::name('SystemAuthNode')->where('path',$path)->find();

		switch (intval($node['auth'])){
			case 0:     // 免登录
				return true;
				break;
			case 1:     // 验证登录
				return !!$admin_id;
				break;
			case 2:     // 验证授权
				break;
		}

        $access = $this->getAllAcess();
		
		return in_array($node['id'],$access);
	}

    /**
     * 获取当前用户全部权限 节点ID
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
	public function getAllAcess(){

        static $access;
        if (empty($access)){
            $admin_id = Session::get('admin.id');

            $roles = Db::name('SystemAuthMap')
                ->alias('m')
                ->join('__SYSTEM_ROLE__ r','r.id=m.role_id')
                ->where('m.admin_id',$admin_id)
                ->select();

            $access = [];

            foreach ($roles as $role) {
                $access = array_merge($access,explode(',',$role['access_list']));
            }

            $access = array_unique($access);
        }

        return $access;
    }
}